package com.alter.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.alter.config.Constants;
import com.alter.util.HttpClientUtil;

@Component
public class SendMbCode {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//验证码过期时间，秒
    private double LIMIT_TIME = 60.0D;
    
    private String pattern = "^1[3-8]\\d{9}";
    
    private static Map<String,Long> sendTimeMap = new HashMap<String,Long>();
    
    private static Map<String,Integer> sendNumMap = new HashMap<String,Integer>();
	
	public JSONObject getVerifyCode(String mobile){
		JSONObject data = new JSONObject();
		if(StringUtils.isEmpty(mobile)){
			data.put("ret", -1008);
	    	data.put("msg", "手机号不能为空");
	    	data.put("data", "");
	    	return data;
		}
		
		String pattern = "^1[3-8]\\d{9}";
		//验证手机号码是否合法
		if(!mobile.matches(pattern)){
		    data.put("ret", -1009);
	    	data.put("msg", "手机号码格式不正确");
	    	data.put("data", "");
	    	return data;
		}
		
		//验证是否重复发送
        long checkTime = new Date().getTime();
        //int number = 0;
        if(sendNumMap.get(mobile) != null){
            float btTime = (checkTime - sendTimeMap.get(mobile))/1000;
            //检测是否频繁发送
            if(btTime < LIMIT_TIME)
            {
            	data.put("ret", -1010);
    	    	data.put("msg", "验证码已发送，请输入或稍后再获取");
    	    	data.put("data", "");
    	    	return data;
            }
//            number = sendNumMap.get(mobile);
//            if(number == *)
//            {
//            	data.put("ret", -1010);
//    	    	data.put("msg", "每个号码每天只能获取*次短信验证码");
//    	    	data.put("data", "");
//    	    	return data;
//            }
        }
        String mbCode = getVailtCode();
		String url = Constants.BASE_URL + Constants.operation;
		String body = "accountSid=" + Constants.ACCOUNT_SID + "&to=" + mobile + "&templateid=63234009&param="+mbCode+",1"
				+ HttpClientUtil.createCommonParam();

		// 提交请求
		String resultStr = HttpClientUtil.post(url, body);
		logger.info("@@@@@@秒滴通道短信验证码发送完毕：返回数据：" + resultStr + "@@@@@@");
        if(!StringUtils.isEmpty(resultStr)){
        	Map resultMap = JSONObject.parseObject(resultStr);
        	String respCode = (String) resultMap.get("failCount");
        	//String replaceAll = respCode.replaceAll("\"", "");
        	int parseInt = Integer.parseInt(respCode);
        	if( parseInt >= 1 ){
        		logger.error("秒滴通道发送验证码异常，异常信息为："+ resultMap.get("failList"));
        	}else{
        		// 将认证码存入SESSION
                long createTime = new Date().getTime();
                //记录发送验证码时间
                sendTimeMap.put(mobile, createTime);
                //记录同一号码发送次数
                //发送次数加1
                //sendNumMap.put(mobile, number);
                data.put("ret", 1);
		    	data.put("msg", "发送成功");
		    	data.put("data", mobile + "|" + mbCode + "|" + createTime);
		    	return data;
            }
        }
        data.put("ret", 0);
    	data.put("msg", "发送失败");
    	data.put("data", "");
		return data;
	}
	
	/**获取短信验证码
     * @return
     */
    public String getVailtCode()
    {
        String random = "" ; 
        for (int i = 0; true ; i++)
        {
            random = (Math.random() * 1000000) + ""  ;
            if( !StringUtils.isEmpty(random) && random.contains("."))
            {
                String[] randoms = random.split("\\.") ;
                random = randoms[0] ;
            }
            if(random.length()>4)
            {
                break ;
            }
        }
        //获取4位验证码
        return random.substring(0,4); 
    }

}
